﻿using Mad.Core.DomainServices;
using NLog;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mad.Infrastructure.DomainServices
{
    public class FileLoggerService : ILoggerService
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public void LoggerInfo(string text)
        {
            logger.Log(LogLevel.Info, text);
        }
        
        public void LoggerInfo(List<string> list)
        {
            var fileTarget = GetLogFileName("logfile");
            if (File.Exists(fileTarget))
            {
                File.Delete(fileTarget);
            }

            foreach (var item in list) LoggerInfo(item);
        }


        public void OpenLogger()
        {
            var fileTarget = GetLogFileName("logfile");

            if (!File.Exists(fileTarget))
                throw new Exception("Log file does not exist.");
            else
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = "notepad.exe";
                proc.StartInfo.Arguments = fileTarget;
                proc.Start();
                proc.Dispose();
            }
        }

        public string GetLogFileName(string targetName)
        {
            string rtnVal = string.Empty;

            if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
            {
                NLog.Targets.Target t = LogManager.Configuration.FindTargetByName(targetName);
                if (t != null)
                {
                    NLog.Layouts.Layout layout = (t as NLog.Targets.FileTarget).FileName;
                    rtnVal = layout.Render(LogEventInfo.CreateNullEvent());
                }
            }

            return rtnVal;
        }
    }
}
